<template>
  <el-checkbox-group v-model="selectvalue" @change="changeParent">
    <el-checkbox v-for="item in options" :key="item.dictValue" :label="item.dictValue" text="item.i18Name">{{ item.i18Name }}</el-checkbox>
  </el-checkbox-group>
</template>

<script>
  import {
    getListDefaults
  } from '@/api/adminPage/attributeDefinition/materials'
export default {
  props: { dictType: { type: String },
    value: {
      type: String
    },
    multiple: String,
    sysType: {
      type: String// tenant代表租户，其他代表平台，默认租户
    }

  },
  data() {
    return {
      options: [],
      selectvalue: [],
      multiples: false,
      optionMap: new Map()
    }
  },
  watch: {
    value: function(newVal) {
      this.selectvalue = newVal.join(',')
    },
    selectvalue: function(newVal, oldVal) {
      if (newVal !== oldVal) {
        if (Array.isArray(newVal)) {
          this.$emit('input', newVal.join(','))
        } else {
          this.$emit('input', newVal)
        }
      }
    }
  }, created() {
    let sysType
    if (this.sysType && this.sysType === 'tenant') {
      sysType = 2
    } else {
      sysType = 1
    }
    // 获取字典值
    const query = {
      dictCode: this.dictType
    }
    const that = this
    const options = this.utils.storage.get(this.dictType) || []
    if (options && options.length) {
      that.options = options
      return false
    }
    getList(query, sysType).then(response => {
      that.options = response.result
      this.utils.storage.save(this.dictType, response.result)
      // 初始化map对象
      that.options.forEach(row => {
        const obj = {}
        obj.lable = row.i18Name
        obj.value = row.dictValue
        this.optionMap.set(row.dictValue, obj)
      })
    })
    this.selectvalue = this.value.split(',')
  }, methods: {
    changeParent() {
      const changevalue = this.selectvalue
      const array = []
      if (Array.isArray(changevalue)) {
        changevalue.forEach(row => {
          if (this.optionMap.get(row)) { array.push(this.optionMap.get(row)) }
        })

        this.$emit('selected', array)
      } else {
        if (this.optionMap.get(changevalue)) { array.push(this.optionMap.get(changevalue)) }
        this.$emit('selected', array)
      }
    },
    stringToBoolean(str) {
      switch (str.toLowerCase()) {
        case 'true': case 'yes': case '1': return true
        case 'false': case 'no': case '0': case null: return false
        default: return Boolean(str)
      }
    }

  }
}
</script>

<style>
</style>
